//插件加载
import plugin from '../../../../lib/plugins/plugin.js'
import data from '../../model/XiuxianData.js'
import fs, { write } from "fs"
import path from "path"
import { Add_najie_thing, Add_player_学习功法, Add_灵石, Read_najie, Write_najie, __PATH } from "../Xiuxian/xiuxian.js"
import { existplayer, ForwardMsg, Read_player,isNotNull,exist_najie_thing} from "../Xiuxian/xiuxian.js"

/**
 * 冒险家协会byDD斩首(3196383818)
 */

export class Forum extends plugin {
    constructor() {
        super({
            name: 'Forum',
            dsc: '修仙模块',
            event: 'message',
            priority: 600,
            rule: [
                {
                    reg: '^#冒险家协会$',
                    fnc: 'Searchforum'
                },
                {
                    reg: '^#发布委托.*$',
                    fnc: 'Pushforum'
                },
                {
                    reg: '^#接受委托.*$',
                    fnc: 'Pu'
                },
                {
                    reg: '^#取消委托.*$',
                    fnc: 'off'
                },

            ]
        })
    }

    async off(e){
        if (!e.isGroup) {
            return;
        }
        let usr_qq = e.user_id;
        if (usr_qq == 80000000) {
            return;
        }
        let ifexistplay = await existplayer(usr_qq);
        if (!ifexistplay) {
            return;
        }
        // e.reply("功能修复中")
        // return
        let title0 = e.msg.replace("#", '');
        title0 = title0.replace("取消委托", '');
        title0=Number(title0)
        let F;
        try {
            F = await Read_Forum();
        }
        catch {
            await Write_Forum([]);
            F = await Read_Forum();
        }
        let guihuan=0;
        let number=0;
        let jiage
        //找到并删掉
        for(var i=0;F.length>i;i++){
            if(F[i].usr==usr_qq&&F[i].number==title0){
                var thingless=F[i]
                jiage=Number(thingless.thingJIAGE)
                await Add_灵石(usr_qq,jiage)
                guihuan+=jiage
                number+=1
                let weizhi=Number(thingless.weizhi)
                F.splice(weizhi,1);//删除
                await Write_Forum(F)
            }
        }
        await genxinliebiao(F)
        if(number==0){
            e.reply("你没有发过该委托呢")
            return
        }

        e.reply("成功取消所有委托，已归还委托金"+guihuan)
    }

    async Pu(e) {
        let usr_qq=e.user_id
        if (!e.isGroup) {
            return;
        }
        // e.reply("功能修复中")
        // return
        if (usr_qq == 80000000) {
            return;
        }
        let ifexistplay = await existplayer(usr_qq);
        if (!ifexistplay) {
            return;
        }

        let title0 = e.msg.replace("#", '');
        title0 = title0.replace("接受委托", '');
        title0=Number(title0)
        let F;
        try {
            F = await Read_Forum();
        }
        catch {
            await Write_Forum([]);
            F = await Read_Forum();
        }
        for(var i=0;F.length>i;i++){
            if(F[i].number==title0){
                var thingless=F[i]
            }
        }
        if(!isNotNull(thingless)){
            e.reply("冒险家协会暂时没有关于他的委托")
            return
        }
        if(thingless.usr==usr_qq){
            e.reply("凯瑟琳:？")
            return
        }

        let najieNumber=await exist_najie_thing(usr_qq,thingless.thing.name,thingless.thing.class)
        if(najieNumber<thingless.thingNumber){
            e.reply("你没有这么多东西提交委托")
            return
        }
        let n=Number(thingless.thingNumber)
        await Add_najie_thing(usr_qq,thingless.thing.name,thingless.thing.class,-n)

        // let A_najie=Read_najie(thingless.usr)
        // let najieNumber2=await exist_najie_thing(thingless.usr,thingless.thing.name,thingless.thing.class)
        // if(isNotNull(najieNumber2)){
        //     najieNumber2=0
        // }
        await Add_najie_thing(thingless.usr,  thingless.thing.name,  thingless.thing.class,  n)
        let najieNumber3=await exist_najie_thing(thingless.usr,thingless.thing.name,thingless.thing.class)
        // if(najieNumber2+n!=najieNumber3){
        //     let wup
        //     if(thingless.thing.class=="丹药"){
        //         thing = A_najie.丹药.find(item=>item.name==thingless.thing.name);
        //         if(!isNotNull(thing)){
        //             wup=thing
        //         }
        //     }

        //     if(thingless.thing.class=="装备"){
        //         thing = A_najie.装备.find(item=>item.name==thingless.thing.name);
        //         if(!isNotNull(thing)){
        //             wup=thing
        //         }
        //     }

        //     if(thingless.thing.class=="材料"){
        //         thing = A_najie.材料.find(item=>item.name==thingless.thing.name);
        //         if(!isNotNull(thing)){
        //             wup=thing
        //         }
        //     }

        //     if(thingless.thing.class=="道具"){
        //         thing = A_najie.道具.find(item=>item.name==thingless.thing.name);
        //         if(!isNotNull(thing)){
        //             wup=thing
        //         }
        //     }

        //     if(thingless.thing.class=="功法"){
        //         thing = A_najie.功法.find(item=>item.name==thingless.thing.name);
        //         if(!isNotNull(thing)){
        //             wup=thing
        //         }
        //     }

        //     if(thingless.thing.class=="草药"){
        //         thing = A_najie.草药.find(item=>item.name==thingless.thing.name);
        //         if(!isNotNull(thing)){
        //             wup=thing
        //         }
        //     }

        //     if(thingless.thing.class=="盒子"){
        //         thing = A_najie.盒子.find(item=>item.name==thingless.thing.name);
        //         if(!isNotNull(thing)){
        //             wup=thing
        //         }
        //     }

        //     wup.数量=najieNumber2+n
        //     await Write_najie(thingless.usr,A_najie)
        //     e.reply("数量不正确，已修复")
        // }
        await Add_灵石(usr_qq,thingless.thingJIAGE)
        let weizhi=Number(thingless.weizhi)
        F.splice(weizhi,1);//删除
        await Write_Forum(F)
        await genxinliebiao(F)
        e.reply("成功接受委托,获得灵石"+thingless.thingJIAGE)




        return;
    }




    async Searchforum(e) {
         //不开放私聊功能
         if (!e.isGroup) {
            return;
        }
        
        let Forum;
        try {
            Forum = await Read_Forum();
        }
        catch {
            await Write_Forum([]);
            Forum = await Read_Forum();
        }
        let msg = [
            "___[冒险家协会]___"
        ];
        for (var i = 0; i < Forum.length; i++) {
            msg.push(
                "   ["+Forum[i].title+"]"+
                "\ntime:"+Forum[i].time+
                "\n需要物品:"+Forum[i].thing.name+
                "\n所需数量:"+Forum[i].thingNumber+
                "\n委托类型:"+Forum[i].thing.class+
                "\n委托金额:"+Forum[i].thingJIAGE+
                "\nID:" + Forum[i].number);
        }
        await ForwardMsg(e, msg);
        return;
    }

    async Pushforum(e) {
        if (!e.isGroup) {
            return;
        }
        let usr_qq = e.user_id;
        if (usr_qq == 80000000) {
            return;
        }
        let ifexistplay = await existplayer(usr_qq);
        if (!ifexistplay) {
            return;
        }
        let Forum;
        try {
            Forum = await Read_Forum();
        }
        catch {
            await Write_Forum([]);
            Forum = await Read_Forum();
        }
        //标题
        let title0 = e.msg.replace("#", '');
        title0 = title0.replace("发布委托", '');
        //内容
        let code = title0.split("\*");
        let thing_name = code[0];//东西
        let thing_amount = code[1];//数量
        let thing_value = code[2];//价格

        if (thing_name.length == 0) {
            e.reply("未填写需求");
            return;
        }
        else if (thing_amount == undefined) {
            e.reply("未填写需求数量");
            return;
        }
        else if (thing_value == undefined) {
            e.reply("未填写委托金额");
            return;
        }
        if (thing_amount<0) {
            e.reply("凯瑟琳:故意找茬是吧")
            return
        }
        if (thing_value<0) {
            e.reply("凯瑟琳:故意找茬是吧")
            return
        }
        let player=await Read_player(usr_qq)
        console.log(player.灵石)
        if(thing_value>player.灵石||player.灵石<0){
            e.reply("很明显您身上的灵石不足以支付委托金呢")
            return
        }

        if (thing_amount < 1 || thing_amount == null || thing_amount == undefined || thing_amount == NaN) {
            thing_amount = 1;
        }
        if (thing_value <= 0) {
            return;
        }
        if (!isNaN(parseFloat(thing_value)) && isFinite(thing_value)) {
        } else {
            return;
        }
        if (!isNaN(parseFloat(thing_amount)) && isFinite(thing_amount)) {
        } else {
            return;
        }
        //判断列表中是否存在，不存在不能卖,并定位是什么物品
        var z = 0;//默认是丹药
        //查找丹药列表
        let ifexist0 = data.danyao_list.find(item => item.name == thing_name);
        //查找道具列表
        let ifexist1 = data.daoju_list.find(item => item.name == thing_name);
        //查找功法列表
        let ifexist2 = data.gongfa_list.find(item => item.name == thing_name);
        //查找装备列表
        let ifexist3 = data.equipment_list.find(item => item.name == thing_name);
        //查找药草列表
        let ifexist4 = data.caoyao_list.find(item => item.name == thing_name);
        //查找限定列表
        let ifexist5 = data.timegongfa_list.find(item => item.name == thing_name);
        let ifexist6 = data.timedanyao_list.find(item => item.name == thing_name);
        let ifexist7 = data.timeequipmen_list.find(item => item.name == thing_name);
        

        if (ifexist0) {
            ifexist0 = ifexist0;
        }
        else if (ifexist1) {
            ifexist0 = ifexist1;
        }
        else if (ifexist2) {
            ifexist0 = ifexist2;
        }
        else if (ifexist3) {
            ifexist0 = ifexist3;
        }
        else if (ifexist4) {
            ifexist0 = ifexist4;
        }
        else if (ifexist5) {
            ifexist0 = ifexist5;
        }
        else if (ifexist6) {
            ifexist0 = ifexist6;
        }
        else if (ifexist7) {
            ifexist0 = ifexist7;
        }
        else {
            e.reply(`这方世界没有这样的东西:${thing_name}`);
            return;
        }


        // let now_level_id;
        // if (!isNotNull(player.level_id)) {
        //     e.reply("请先#同步信息");
        //     return;
        // }
        
        // now_level_id = data.Level_list.find(item => item.level_id == player.level_id).level_id;
        // if(now_level_id<9){
        //     e.reply("境界过低");
        //     return;
        // }
        await Add_灵石(usr_qq,-thing_value)
        //随机编号
        let Mathrandom = Math.random();
        Mathrandom=usr_qq+Mathrandom
        Mathrandom=Mathrandom*100000
        Mathrandom = Math.trunc(Mathrandom);
        
        //时间
        var myDate = new Date();
        var year = myDate.getFullYear(); //获取完整的年份(4位,1970-????)
        var month = myDate.getMonth()+1;  //获取当前月份(1-12)
        var day = myDate.getDate();  //获取当前日(1-31)
        var newDay = year + '-' + month + '-' + day;//获取完整年月日
        let wupin = {
            "title": thing_name,//发布名
            "qq": usr_qq,//发布名
            "time": newDay,//发布时间
            "number":Mathrandom,//编号
            "thing":ifexist0,
            "thingNumber":thing_amount,
            "thingJIAGE":thing_value,
            "usr":e.user_id,
            "weizhi":Forum.length
        };
        Forum.push(wupin);
        await Write_Forum(Forum);
        e.reply("发布成功！花费"+thing_value+"灵石");
        return;
    }

}

//写入
export async function Write_Forum(wupin) {
    let dir = path.join(__PATH.Forum, `Forum.json`);
    let new_ARR = JSON.stringify(wupin, "", "\t");
    fs.writeFileSync(dir, new_ARR, 'utf8', (err) => {
        console.log('写入成功', err)
    })
    return;
}
//更新下标
export async function genxinliebiao(Forum) {
    for(var i=0;Forum.length>i;i++){
        if(Forum[i].weizhi==0){

        }else{
            Forum[i].weizhi-=1
        }
        await Write_Forum(Forum)
    }
    return;
}

//读取
export async function Read_Forum() {
    let dir = path.join(`${__PATH.Forum}/Forum.json`);
    let Forum = fs.readFileSync(dir, 'utf8', (err, data) => {
        if (err) {
            console.log(err)
            return "error";
        }
        return data;
    })
    Forum = JSON.parse(Forum);
    return Forum;
}
